const constant = require('../../components/constant');
const request = require('../../components/request');
const pageInterceptor = require('../../components/pageInterceptor').pageInterceptor;
const {
  ViewStockTransactionData
} = require('../../view/ViewStockTransactionData');
const {
  ViewStockPriceReminder
} = require('../../view/ViewStockPriceReminder');
const {
  validatePrice,
  validatePercentage
} = require('../../components/util');
const {StockPriceReminderVo} = require('../../vo/StockPriceReminderVo');

// Page({
pageInterceptor({
  /**
   * 页面的初始数据
   */
  data: {
    /**
     * 跳转到这个页面的路径
     */
    path: undefined,

    /**
     * 股票交易数据列表
     */
    viewStockTransactionDataList: [],

    /**
     * 股票交易数据
     */
    viewStockTransactionData: {},

    /**
     * 股票的代码或名称
     */
    codeOrName: '',

    /**
     * 提醒输入框是否隐藏
     */
    reminderHidden: true,

    /**
     * 全选checkbox是否被选中
     */
    allSelect: false,
    
    /**
     * 股价提醒--弹出窗口
     */
    viewStockPriceReminder: new ViewStockPriceReminder(),

    // /**
    //  * 股价上涨达到
    //  */
    // stockPriceUp: null,

    // /**
    //  * 股价下跌达到
    //  */
    // stockPriceDown: null,

    // /**
    //  * 日涨跌幅达到
    //  */
    // changeRange: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getViewStockTransactionDataRegularly();
    setInterval(this.getViewStockTransactionDataRegularly, constant.timing.timeForGettingViewStockTransactionDataRegularly);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  /**
   * 订阅股票
   */
  subscribeStock: function (e) {
    let stockInfo = e.detail.value.stockInfo;
    console.log(`用户订阅的股票是：${stockInfo}`);

    // 如果没有输入股票代码或名称，则直接返回，并弹出提示框
    if (stockInfo == '') {
      const message = '没有输入股票代码或名称';
      console.warn(message);
      wx.showToast({
        title: message,
        icon: 'none',
        duration: 3000
      });
      return;
    }

    let user = wx.getStorageSync('user');

    let _this = this;
    let _user = JSON.stringify(user);
    request.post(constant.api.data.prefix + constant.api.data.url.subscribeStock, {
      stockInfo
    }, {
      'content-type': 'application/json',
      'user': _user,
    }).action((res) => {
      console.log(`调用接口${constant.api.data.url.subscribeStock}，返回值为${res}`);
      // 判断是否有这支股票的交易记录，如果没有则展示提示框
      if (res.data.success == false) {
        console.warn(`${res.data.message}`);
        wx.showToast({
          title: res.data.message,
          icon: 'none',
          duration: 3000
        });
        return;
      }
      // 前台页面显示的股票数据
      let _viewStockTransactionDataList = _this.data.viewStockTransactionDataList;
      // 从服务端获取地股票数据
      let viewStockTransactionData = new ViewStockTransactionData(res.data.data);
      // 表示订阅的股票是否已经在前台展示
      let exist = false;
      for (let i = 0; i < _viewStockTransactionDataList.length; i++) {
        if (viewStockTransactionData.code == _viewStockTransactionDataList[i].code) {
          exist = true;
        }
      }
      // 如果订阅的股票没有在前台展示，则将订阅的股票添加到本地存储中，并放到前台展示
      if (!exist) {
        console.info(`订阅的股票是【${viewStockTransactionData.code}】新股票，将其存储在本地，并在前台展示`);
        _viewStockTransactionDataList.push(viewStockTransactionData);
        // 将订阅的股票添加到本地存储中
        let user = wx.getStorageSync('user');
        user.stockCodeList = [];
        for (let i = 0; i < _viewStockTransactionDataList.length; i++) {
          user.stockCodeList.push(_viewStockTransactionDataList[i].code);
        }
        wx.setStorageSync('user', user);
        // 将订阅的股票放到前台展示
        _this.setData({
          'viewStockTransactionDataList': _viewStockTransactionDataList,
          'codeOrName': '',
        });
        this.onLoad();
      }
    }).catch(err => {
      console.warn(err);
    });
  },

  /**
   * 定时地获取订阅的股票交易数据
   */
  getViewStockTransactionDataRegularly: function () {
    console.info(`时间：${new Date()}，开始定时地获取订阅的股票交易数据`);

    let user = wx.getStorageSync('user');
    let stockCodeList = user.stockCodeList;

    let _this = this;
    let _user = JSON.stringify(user);

    request.post(constant.api.data.prefix + constant.api.data.url.findStockTransactionList, {
      userId: user.userId,
      stockCodeList
    }, {
      'content-type': 'application/json',
      'user': _user,
    }).action((res) => {
      let _viewStockTransactionDataList = ViewStockTransactionData.toViewStockTransactionDataList(res.data.data);
      if (_viewStockTransactionDataList && _viewStockTransactionDataList.length) {
        let viewStockTransactionDataList = [];
        let stockCodeList = [];
        let oldViewStockTransactionDataList = this.data.viewStockTransactionDataList;
        for (let i = 0; i < _viewStockTransactionDataList.length; i++) {
          // 每次调用接口获取到的交易数据中没有是否被选中这一项，因此新数据需要和老数据进行比较，如果之前被选中了，那么要一直保持被选中。否则每次调用接口之后，都会变成没有被选中
          for (let j = 0; j < oldViewStockTransactionDataList.length; j++) {
            if (_viewStockTransactionDataList[i].code == oldViewStockTransactionDataList[j].code && oldViewStockTransactionDataList[j].checked == true) {
              _viewStockTransactionDataList[i].checked = true;
            }
          }
          viewStockTransactionDataList.push(_viewStockTransactionDataList[i]);
          stockCodeList.push(_viewStockTransactionDataList[i]);
        }
        _user.stockCodeList = stockCodeList;
        wx.setStorageSync('user', JSON.parse(_user));
        _this.setData({
          viewStockTransactionDataList: viewStockTransactionDataList
        })
      }
    }).catch(err => {}); //异常回调
  },

  /**
   * 全选股票
   * @param {*} e 
   */
  allStockSelectChange: function (e) {
    console.info(e.detail.value);

    let checkboxList = e.detail.value;
    // 当选中全选checkbox时，所有checkbox都被选中
    if (checkboxList.length > 0) {
      let _viewStockTransactionDataList = this.data.viewStockTransactionDataList;
      for (let i = 0; i < _viewStockTransactionDataList.length; i++) {
        _viewStockTransactionDataList[i].checked = true;
      }
      this.setData({
        viewStockTransactionDataList: _viewStockTransactionDataList,
      });
    };
    // 当取消全选checkbox时，所有checkbox都被取消
    if (checkboxList.length == 0) {
      let _viewStockTransactionDataList = this.data.viewStockTransactionDataList;
      for (let i = 0; i < _viewStockTransactionDataList.length; i++) {
        _viewStockTransactionDataList[i].checked = false;
      }
      this.setData({
        viewStockTransactionDataList: _viewStockTransactionDataList,
      });
    };
  },

  /**
   * 多选股票
   * @param {*} e 
   */
  multiStockSelectChange: function (e) {
    let codeArray = e.detail.value;
    console.info(`被勾选的股票代码列表：${codeArray}`);

    let _viewStockTransactionDataList = this.data.viewStockTransactionDataList;
    // 已经订阅的股票的数量
    let listLength = _viewStockTransactionDataList.length;
    // 表示被勾选的股票的数量
    let selectNumber = 0;
    // 如果这个股票被勾选，则将其的checked属性设置为true
    for (let i = 0; i < _viewStockTransactionDataList.length; i++) {
      _viewStockTransactionDataList[i].checked = false;
      for (let j = 0; j < codeArray.length; j++) {
        if (_viewStockTransactionDataList[i].code == codeArray[j]) {
          _viewStockTransactionDataList[i].checked = true;
          selectNumber++;
          break;
        }
      }
    }
    // 更新表格中的checkbox
    this.setData({
      viewStockTransactionDataList: _viewStockTransactionDataList,
    });
    // 如果所有的checkbox都被选中，则全选checkbox也被勾选
    if (selectNumber == listLength) {
      this.setData({
        allSelect: true,
      });
    };
    // 如果所有的checkbox都没有被选中，则全选checkbox也被取消
    if (selectNumber != listLength) {
      this.setData({
        allSelect: false,
      });
    }
  },

  /**
   * 删除订阅的股票
   */
  deleteSubscription: function (e) {
    if (!this.data.viewStockTransactionDataList) {
      // 如果没有订阅任何股票则弹出提示框
      let message = '没有订阅任何股票';
      console.warn(message);
      wx.showToast({
        title: message,
        icon: 'none',
        duration: 3000
      });
    } else {
      let _viewStockTransactionDataList = this.data.viewStockTransactionDataList;
      let deleteSubscriptionList = [];
      for (let i = 0; i < _viewStockTransactionDataList.length; i++) {
        if (_viewStockTransactionDataList[i].checked == true) {
          deleteSubscriptionList.push(_viewStockTransactionDataList[i].code);
        }
      }
      let user = wx.getStorageSync('user');
      let _user = JSON.stringify(user);
      request.post(constant.api.data.prefix + constant.api.data.url.deleteSubscription, {
        deleteSubscriptionList,
      }, {
        'content-type': 'application/json',
        'user': _user,
      }).action((response) => {
        console.info(response);

        // 删除订阅股票后，storage中的user.stockCodeList也要同步
        let user = wx.getStorageSync('user');
        let stockCodeList = user.stockCodeList;
        let newStockCodeList = [];
        for (let i = 0; i < stockCodeList.length; i++) {
          let deletedStock = false;
          for (let j = 0; j < deleteSubscriptionList.length; j++) {
            if (stockCodeList[i] == deleteSubscriptionList[j]) {
              deletedStock = true;
              break;
            }
          }
          if (!deletedStock) {
            newStockCodeList.push(stockCodeList[i]);
          }
        }
        user.stockCodeList = newStockCodeList;
        wx.setStorageSync('user', user);

        // 删除订阅股票后，前端表格和data.viewStockTransactionDataList都要更新
        // 更新data.viewStockTransactionDataList
        let newViewStockTransactionDataList = [];
        for (let i = 0; i < _viewStockTransactionDataList.length; i++) {
          let deletedStock = false;
          for (let j = 0; j < deleteSubscriptionList.length; j++) {
            if (_viewStockTransactionDataList[i].code == deleteSubscriptionList[j]) {
              deletedStock = true;
              break;
            }
          }
          if (!deletedStock) {
            newViewStockTransactionDataList.push(_viewStockTransactionDataList[i]);
          }
        }
        // 更新前端表格
        this.setData({
          viewStockTransactionDataList: newViewStockTransactionDataList,
        });
      }).catch(err => {});
    }
  },

  /**
   * 提醒图标
   * @param {*} data 
   */
  remind: function (data) {
    let code = data.currentTarget.dataset.code;
    console.info(`弹出对话框，显示股票${code}的提醒信息`);

    // 更新this.data.viewStockPriceReminder对象
    this.data.viewStockPriceReminder.stockCode = code;
    // 展示对话框
    this.setData({
      reminderHidden: false,
      viewStockPriceReminder: this.data.viewStockPriceReminder
    });
  },

  /**
   * 验证“股价上涨达到”input
   * @param {*} e 
   */
  validateStockPriceUp: function (e) {
    let stockPriceUp = e.detail.value;

    // 如果是空字符串，则不做验证
    if (stockPriceUp.trim() == '') {
      // 刷新前台
      this.data.viewStockPriceReminder.stockPriceUpCheck = true;
      this.data.viewStockPriceReminder.stockPriceUp = stockPriceUp;
      this.data.viewStockPriceReminder.stockPriceUpValid = false;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
      return;
    }

    console.info(`股价上涨达到${stockPriceUp}`);

    // 验证价格
    let valid = validatePrice(stockPriceUp);
    if (!valid) {
      // 如果价格不合法，则弹出提示框
      let invalidMessage = `价格【${stockPriceUp}】不合法`;
      wx.showToast({
        title: invalidMessage,
        icon: 'none',
        duration: 3000
      });
      // 刷新前台
      this.data.viewStockPriceReminder.stockPriceUpValid = false;
      this.data.viewStockPriceReminder.stockPriceUp = stockPriceUp;
      this.data.viewStockPriceReminder.stockPriceUpInvalidMessage = invalidMessage;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    } else {
      // 刷新前台
      this.data.viewStockPriceReminder.stockPriceUp = stockPriceUp;
      this.data.viewStockPriceReminder.stockPriceUpValid = true;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }
  },

  /**
   * 验证“股价下涨达到”input
   * @param {*} e 
   */
  validateStockPriceDown: function (e) {
    let stockPriceDown = e.detail.value;

    // 如果是空字符串，则不做验证
    if (stockPriceDown.trim() == '') {
      // 刷新前台
      this.data.viewStockPriceReminder.stockPriceDownCheck = true;
      this.data.viewStockPriceReminder.stockPriceDown = stockPriceDown;
      this.data.viewStockPriceReminder.stockPriceDownValid = false;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
      return;
    }

    console.info(`股价下涨达到${stockPriceDown}`);

    // 验证价格
    let valid = validatePrice(stockPriceDown);
    if (!valid) {
      // 如果价格不合法，则弹出提示框
      let invalidMessage = `价格【${stockPriceDown}】不合法`;
      wx.showToast({
        title: invalidMessage,
        icon: 'none',
        duration: 3000
      });
      // 刷新前台
      this.data.viewStockPriceReminder.stockPriceDownValid = false;
      this.data.viewStockPriceReminder.stockPriceDown = stockPriceDown;
      this.data.viewStockPriceReminder.stockPriceDownInvalidMessage = invalidMessage;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    } else {
      // 刷新前台
      this.data.viewStockPriceReminder.stockPriceDownValid = true;
      this.data.viewStockPriceReminder.stockPriceDown = stockPriceDown;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }
  },

  /**
   * 验证“日涨跌幅达到”input
   * @param {*} e 
   */
  validateChangeRange: function (e) {
    let changeRange = e.detail.value;

    // 如果是空字符串，则不做验证
    if (changeRange.trim() == '') {
      // 刷新前台
      this.data.viewStockPriceReminder.changeRange = true;
      this.data.viewStockPriceReminder.changeRange = changeRange;
      this.data.viewStockPriceReminder.changeRangeValid = false;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
      return;
    }

    console.info(`日涨跌幅达到${changeRange}`);

    // 验证价格
    let valid = validatePercentage(changeRange);
    if (!valid) {
      // 如果价格不合法，则弹出提示框
      let invalidMessage = `百分比【${changeRange}】不合法`;
      wx.showToast({
        title: invalidMessage,
        icon: 'none',
        duration: 3000
      });
      // 刷新前台
      this.data.viewStockPriceReminder.changeRangeValid = false;
      this.data.viewStockPriceReminder.changeRange = changeRange;
      this.data.viewStockPriceReminder.changeRangeInvalidMessage = invalidMessage;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    } else {
      // 刷新前台
      this.data.viewStockPriceReminder.changeRangeValid = true;
      this.data.viewStockPriceReminder.changeRange = changeRange;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }
  },

  /**
   * 选择提醒输入框的提交
   * @param {*} e 
   */
  reminderModalSubmit: function (e) {
    // 如果三个checkbox都没有勾选，则给与提示
    if (this.data.viewStockPriceReminder.stockPriceUpCheck == false &&
      this.data.viewStockPriceReminder.stockPriceDownCheck == false &&
      this.data.viewStockPriceReminder.changeRangeCheck == false) {
      wx.showToast({
        title: '请勾选需要提醒的项目',
        icon: 'none',
        duration: 3000
      });
      return;
    }

    // 保存之前验证时的错误提示
    let invalidMessageList = [];
    if(this.data.viewStockPriceReminder.stockPriceUpCheck == true 
      && this.data.viewStockPriceReminder.stockPriceUpValid == false){
        invalidMessageList.push(this.data.viewStockPriceReminder.stockPriceUpInvalidMessage);
    }
    if(this.data.viewStockPriceReminder.stockPriceDownCheck == true 
      && this.data.viewStockPriceReminder.stockPriceDownValid == false){
        invalidMessageList.push(this.data.viewStockPriceReminder.stockPriceDownInvalidMessage);
    }
    if(this.data.viewStockPriceReminder.changeRangeCheck == true 
      && this.data.viewStockPriceReminder.changeRangeValid == false){
        invalidMessageList.push(this.data.viewStockPriceReminder.changeRangeInvalidMessage);
    }

    if(invalidMessageList.length > 0){
      // 弹出提示框，显示验证错误消息
      wx.showToast({
        // 这个地方网上说，在开发者工具中不行，但是真机中可以，回头测试一下
        title: invalidMessageList.toString().replace(',', '\r\n'),
        icon: 'none',
        duration: 5000
      });
    }else{
      // 验证都通过
      let stockPriceReminderVo = new StockPriceReminderVo();
      stockPriceReminderVo.stockCode = this.data.viewStockPriceReminder.stockCode;
      if(this.data.viewStockPriceReminder.stockPriceUpCheck == true){
        stockPriceReminderVo.stockPriceUp = this.data.viewStockPriceReminder.stockPriceUp;
      }
      if(this.data.viewStockPriceReminder.stockPriceDownCheck == true){
        stockPriceReminderVo.stockPriceDown = this.data.viewStockPriceReminder.stockPriceDown;
      }
      if(this.data.viewStockPriceReminder.changeRangeCheck == true){
        stockPriceReminderVo.changeRange = this.data.viewStockPriceReminder.changeRange;
      }

      let user = wx.getStorageSync('user');
      let _user = JSON.stringify(user);

      // 调用接口
      request.post(constant.api.data.prefix + constant.api.data.url.remindStockPrice, {
        userId: user.userId,
        stockPriceReminderVo
      }, {
        'content-type': 'application/json',
        'user': _user,
      }).action((response) => {
        console.info(response);

        // 关闭股价提醒对话框
        this.setData({
          reminderHidden: true
        });
      }).catch(err => {});
    }
  },

  /**
   * 选择提醒输入框的关闭
   * @param {*} e 
   */
  reminderModalClose: function (e) {
    this.setData({
      reminderHidden: true
    });
  },

  /**
   * 选择提醒输入框的取消提醒
   * @param {*} e 
   */
  cancelReminder: function (e) {
    console.info(e);
  },

  /**
   * checkbox多选提醒项
   * @param {*} e 
   */
  multiReminderSelectChange: function (e) {
    let reminderList = e.detail.value;
    console.info(reminderList);

    // 更新viewStockPriceReminder对象
    if(reminderList.includes(this.data.viewStockPriceReminder.stockPriceUpName)){
      this.data.viewStockPriceReminder.stockPriceUpCheck = true;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }else{
      this.data.viewStockPriceReminder.stockPriceUpCheck = false;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }
    if(reminderList.includes(this.data.viewStockPriceReminder.stockPriceDownName)){
      this.data.viewStockPriceReminder.stockPriceDownCheck = true;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }else{
      this.data.viewStockPriceReminder.stockPriceDownCheck = false;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }
    if(reminderList.includes(this.data.viewStockPriceReminder.changeRangeName)){
      this.data.viewStockPriceReminder.changeRangeCheck = true;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }else{
      this.data.viewStockPriceReminder.changeRangeCheck = false;
      this.setData({
        viewStockPriceReminder: this.data.viewStockPriceReminder
      });
    }
  },
  // })
}, true)